package org.ls.wxscancodes.util;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
public class PageController {
public static  Map<String,String> QR_CODES=new HashMap<>();
    @RequestMapping("/media")
    public String page() {
        return "media";
    }

    @RequestMapping("/code1")
    public void code1(HttpServletResponse resp) throws IOException {
        String jsonStr = "{\"expire_seconds\": 604800, \"action_name\": \"QR_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"login\"}}}";
        String json = httputil.doPost("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=78_EyZWbquzxqJE2ilm779hjjzHs6hW_NXZ3DwybNxKJJ3NZ7NcxcFh4leqZLRB4-ijBY14qYI6_QH1NtMqZTJM-WG4E5erWr2JM9zCPgcdbjKxKKKizpFF-jNihmsZBHgAJACEK", jsonStr, null);
        JSONObject obj = JSONUtil.parseObj(json);
        System.out.println(obj.get("ticket"));
        System.out.println(obj.get("url"));
        System.out.println("走code1++++++++++++++++++++++++++++++++++++++");
        BufferedImage im = QrCodeUtil.generate(obj.getStr("url"), 500, 500);
        ImageIO.write(im, "jpg", resp.getOutputStream());
    }

    @RequestMapping("/code2")
    @ResponseBody
    public Map code2(HttpServletResponse resp) throws IOException {
        String jsonStr = "{\"expire_seconds\": 604800, \"action_name\": \"QR_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"login\"}}}";
        String json = httputil.doPost("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=78_EyZWbquzxqJE2ilm779hjjzHs6hW_NXZ3DwybNxKJJ3NZ7NcxcFh4leqZLRB4-ijBY14qYI6_QH1NtMqZTJM-WG4E5erWr2JM9zCPgcdbjKxKKKizpFF-jNihmsZBHgAJACEK", jsonStr, null);
        JSONObject obj = JSONUtil.parseObj(json);
        Map result = new HashMap();
        result.put("url", "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + obj.getStr("ticket"));
        result.put("ticker",obj.getStr("ticket"));
        return result;
    }

    @RequestMapping("/checkLogin")
    @ResponseBody
    public Map checkLogin(String ticker) throws IOException {
        String s = QR_CODES.get(ticker);
        Map hashMap = new HashMap();
        System.out.println(s+"==============");
        if(s==null){
            hashMap.put("status", "no_login");
        }else {
            hashMap.put("status", "login");
            hashMap.put("user",s);
        }
        return hashMap;
    }

}
